package com.aijk.web.admin.controller.ehm.user;

import com.aijk.commons.exception.ErrorCodeException;
import com.aijk.commons.lang.utils.StringUtil;
import com.aijk.commons.mijo.utils.PojoUtil;
import com.aijk.commons.utils.PasswordHelper;
import com.aijk.commons.utils.Utils;
import com.aijk.ehm.api.*;
import com.aijk.ehm.model.EhmPeopleCrowd;
import com.aijk.ehm.model.EhmResidentCrowd;
import com.aijk.ehm.model.dto.BasUserDto;
import com.aijk.ehm.model.dto.EhmCompanyDeptDto;
import com.aijk.ehm.model.dto.EhmCompanyDto;
import com.aijk.ehm.model.dto.EhmResidentDto;
import com.aijk.ehm.model.qo.*;
import com.aijk.ehm.model.vo.BasUserVo;
import com.aijk.ehm.model.vo.EhmCompanyDeptVo;
import com.aijk.ehm.model.vo.EhmCompanyVo;
import com.aijk.ehm.model.vo.EhmResidentVo;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.utils.*;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户Controller
 */
@Controller
@RequestMapping("/admin/ehm/user")
public class UserController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BasUserApi basUserApi;

    @Autowired
    private EhmResidentApi ehmResidentApi;

    @Autowired
    private EhmCompanyApi ehmCompanyApi;

    @Autowired
    private EhmCompanyDeptApi ehmCompanyDeptApi;

    @Autowired
    private EhmPeopleCrowdApi crowdApi;

    @Autowired EhmResidentCrowdApi ehmResidentCrowdApi;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list_view(Model model) {
        if(isSubCompany()){
            if(isCompany()){
                return "error/no_permissions";
            }
            model.addAttribute("sys_flag",true);
        }else{
            model.addAttribute("sys_flag",false);
        }
        return "ehm/user/list";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg list(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        EhmResidentQo qo = DataTableUtil.fillQo(skey,EhmResidentQo.class);
        if(isSubCompany()){
            qo.setCompanyId(getCurrentUser().getCompanyId());
        }
        draw += 1;
        PageInfo<EhmResidentVo> pageInfo = ehmResidentApi.page(qo);
        iTotalRecords =pageInfo.getTotal();
        RetMsg regMsg = new RetMsg();

        regMsg.put("data", pageInfo.getList());
        regMsg.put("draw", draw);
        regMsg.put("recordsTotal", iTotalRecords);
        regMsg.put("recordsFiltered", iTotalRecords);

        return regMsg;
    }

    /**员工新增、编辑**/
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String add_view(Model model, Long id) {
        EhmResidentVo ehmResidentVo = new EhmResidentVo();
        String companyTitle = "";
        if (id != null){
            ehmResidentVo = ehmResidentApi.findOne(id);
            BasUserVo basUserVo = basUserApi.findOne(ehmResidentVo.getUid());
            ehmResidentVo.setIdCard(basUserVo.getIdcard());
            model.addAttribute("sys_flag",false);//sys_flag 系统标识 true：系统管理员 false:体检中心自身登录

            List<EhmPeopleCrowd> crowds = crowdApi.list(new EhmPeopleCrowdQo());

            //人群分类列表
            model.addAttribute("crowds",crowds);

            EhmResidentCrowdQo ehmResidentCrowdQo = new EhmResidentCrowdQo();
            ehmResidentCrowdQo.setResidentId(id);
            ehmResidentCrowdQo.setUid(ehmResidentVo.getUid());
            List<EhmResidentCrowd> ehmResidentCrowdList = ehmResidentCrowdApi.list(ehmResidentCrowdQo);
            String rids ="";
            if(null!=ehmResidentCrowdList){
                for (EhmResidentCrowd ehmResidentCrowd : ehmResidentCrowdList){
                    rids+=ehmResidentCrowd.getCrowdId()+",";
                }
            }
            if(rids.length()>0){
                model.addAttribute("rids",rids.substring(0,rids.length()-1));
            }
            model.addAttribute("type",0);
            companyTitle = ehmResidentVo.getCompany();
        }else{
             if(isSubCompany()){
            EhmCompanyVo ehmCompanyVo = ehmCompanyApi.findOne(getCurrentUser().getCompanyId());
            companyTitle = ehmCompanyVo.getTitle();
             }
            model.addAttribute("type",-1);
            model.addAttribute("sys_flag",true);//sys_flag 系统标识 true：系统管理员 false:体检中心自身登录
        }
        EhmCompanyDeptQo ehmCompanyDeptQo = new EhmCompanyDeptQo();
        ehmCompanyDeptQo.setCompanyId(getCurrentUser().getCompanyId());
        ehmCompanyDeptQo.setStatus((byte) 10);
        List<EhmCompanyDeptVo> ehmCompanyDeptVos = ehmCompanyDeptApi.list(ehmCompanyDeptQo);

        model.addAttribute("company",companyTitle);
        model.addAttribute("dept",ehmCompanyDeptVos);
        model.addAttribute("data",ehmResidentVo);

        if(isSubCompany()){
            model.addAttribute("sys_flag",true);
        }else{
            model.addAttribute("sys_flag",false);
        }

        return "ehm/user/edit";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg save(EhmResidentDto dto,  String roles) {
        try {
            EhmCompanyVo ehmCompanyVo = ehmCompanyApi.findOne(getCurrentUser().getCompanyId());
            dto.setCompanyId(ehmCompanyVo.getId());
            dto.setCompany(ehmCompanyVo.getTitle());
            EhmCompanyDeptVo ehmCompanyDeptVo = ehmCompanyDeptApi.findOne(dto.getDeptId());
            dto.setDept(ehmCompanyDeptVo.getTitle());
            if (dto.getId() == null){
               if(dto.getUid() == null){
                   BasUserDto basUserDto = new BasUserDto();
                   basUserDto.setCardtype(1);
                   basUserDto.setIdcard(dto.getIdCard());
                   basUserDto.setTitle(dto.getTitle());
                   basUserDto.setSex(Utils.toShort(IdcardUtil.getSex(dto.getIdCard())));
//                   basUserDto.setAddress(dto.getAddress());
                   basUserDto.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(IdcardUtil.getBirch(dto.getIdCard())));
                   basUserDto.setCreated(new Date());
                   basUserDto.setCreater(Utils.toLong(getCurrentUser().getAdminId()));
                   Long uid = basUserApi.save(basUserDto);
                   dto.setUid(uid);
               }
                dto.setCreated(new Date());
                dto.setCreater(getCurrentUser().getAdminId().longValue());
                dto.setCrowd(roles);
                dto.setSn(ConvertUtil.randomString(11));
                dto.setStatus((byte)10);
                dto.setSalt(RandomString.generateRandomString(16));
                dto.setPassword(PasswordHelper.encryptPassword("123456", dto.getSalt()));
                ehmResidentApi.save(dto);
                //企业修改人数
                EhmCompanyVo ehmCompanyVo1 =  ehmCompanyApi.findOne(getCurrentUser().getCompanyId());
                ehmCompanyVo1.setPersonNum(ehmCompanyVo1.getPersonNum()+1);
                EhmCompanyDto ehmCompanyDto = PojoUtil.convert(ehmCompanyVo1,EhmCompanyDto.class);
                ehmCompanyApi.update(ehmCompanyDto);
                //部门修改人数
                EhmCompanyDeptVo ehmCompanyDeptVo1 = ehmCompanyDeptApi.findOne(dto.getDeptId());
                ehmCompanyDeptVo1.setDeptNum(ehmCompanyDeptVo1.getDeptNum()+1);
                EhmCompanyDeptDto ehmCompanyDeptDto = PojoUtil.convert(ehmCompanyDeptVo1 , EhmCompanyDeptDto.class);
                ehmCompanyDeptApi.update(ehmCompanyDeptDto);
            }else {
                //部门修改人数
                EhmResidentVo ehmResidentVo = ehmResidentApi.findOne(dto.getId());
                if(ehmResidentVo.getDeptId() != dto.getDeptId()){
                    EhmCompanyDeptVo ehmCompanyDeptVo1 = ehmCompanyDeptApi.findOne(dto.getDeptId());
                    ehmCompanyDeptVo1.setDeptNum(ehmCompanyDeptVo1.getDeptNum() + 1);
                    EhmCompanyDeptDto ehmCompanyDeptDto = PojoUtil.convert(ehmCompanyDeptVo1 , EhmCompanyDeptDto.class);
                    ehmCompanyDeptApi.update(ehmCompanyDeptDto);

                    EhmCompanyDeptVo ehmCompanyDeptVo2 = ehmCompanyDeptApi.findOne(ehmResidentVo.getDeptId());
                    ehmCompanyDeptVo2.setDeptNum(ehmCompanyDeptVo2.getDeptNum() - 1);
                    EhmCompanyDeptDto ehmCompanyDeptDto2 = PojoUtil.convert(ehmCompanyDeptVo2 , EhmCompanyDeptDto.class);
                    ehmCompanyDeptApi.update(ehmCompanyDeptDto2);
                }

                dto.setModified(new Date());
                dto.setModifier(getCurrentUser().getAdminId().longValue());
                dto.setCrowd(roles);
                ehmResidentApi.update(dto);
            }
        }catch (Exception e){
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    public void saveUserList(List<EhmResidentDto> list){
        try {
            for (EhmResidentDto dto : list){
                if(dto.getUid() == null){
                    BasUserDto basUserDto = new BasUserDto();
                    basUserDto.setCardtype(1);
                    basUserDto.setIdcard(dto.getIdCard());
                    basUserDto.setTitle(dto.getTitle());
                    basUserDto.setSex(Utils.toShort(IdcardUtil.getSex(dto.getIdCard())));
                    basUserDto.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(IdcardUtil.getBirch(dto.getIdCard())));
                    basUserDto.setCreated(new Date());
                    basUserDto.setCreater(Utils.toLong(getCurrentUser().getAdminId()));
                    Long uid = basUserApi.save(basUserDto);
                    dto.setUid(uid);
                }
                dto.setCreated(new Date());
                dto.setCreater(getCurrentUser().getAdminId().longValue());
                dto.setSn(dto.getCompanySn()+ConvertUtil.randomString(8));
                dto.setStatus((byte)10);
                dto.setSalt(RandomString.generateRandomString(16));
                dto.setPassword(PasswordHelper.encryptPassword("123456", dto.getSalt()));
                ehmResidentApi.save(dto);

                EhmCompanyVo ehmCompanyVo1 =  ehmCompanyApi.findOne(getCurrentUser().getCompanyId());
                ehmCompanyVo1.setPersonNum(ehmCompanyVo1.getPersonNum()+1);
                EhmCompanyDto ehmCompanyDto = PojoUtil.convert(ehmCompanyVo1,EhmCompanyDto.class);
                ehmCompanyApi.update(ehmCompanyDto);
                //部门修改人数
                EhmCompanyDeptVo ehmCompanyDeptVo1 = ehmCompanyDeptApi.findOne(dto.getDeptId());
                ehmCompanyDeptVo1.setDeptNum(ehmCompanyDeptVo1.getDeptNum()+1);
                EhmCompanyDeptDto ehmCompanyDeptDto = PojoUtil.convert(ehmCompanyDeptVo1 , EhmCompanyDeptDto.class);
                ehmCompanyDeptApi.update(ehmCompanyDeptDto);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**禁用、启用**/
    @RequestMapping(value = "/status", method = RequestMethod.POST)
    @ResponseBody public RetMsg status(@Valid EhmResidentDto dto) {
        try {
            EhmResidentVo ehmResidentVo = ehmResidentApi.findOne(dto.getId());
            EhmCompanyVo ehmCompanyVo1 =  ehmCompanyApi.findOne(ehmResidentVo.getCompanyId());
            EhmCompanyDeptVo ehmCompanyDeptVo1 = ehmCompanyDeptApi.findOne(ehmResidentVo.getDeptId());
            if((ehmCompanyVo1.getStatus() & 0xff) == 10 && (ehmCompanyDeptVo1.getStatus() & 0xff) == 10 ){
                dto.setModifier(Utils.toLong(getCurrentUser().getAdminId()));
                dto.setModified(new Date());
                ehmResidentApi.update(dto);
                Integer status = dto.getStatus() & 0xff;
                //修改人数
                if(status == 20){
                    ehmCompanyVo1.setPersonNum(ehmCompanyVo1.getPersonNum() - 1);
                    ehmCompanyDeptVo1.setDeptNum(ehmCompanyDeptVo1.getDeptNum() - 1);
                }
                if(status == 10){
                    ehmCompanyVo1.setPersonNum(ehmCompanyVo1.getPersonNum() + 1);
                    ehmCompanyDeptVo1.setDeptNum(ehmCompanyDeptVo1.getDeptNum() + 1);
                }
                EhmCompanyDto ehmCompanyDto = PojoUtil.convert(ehmCompanyVo1,EhmCompanyDto.class);
                EhmCompanyDeptDto ehmCompanyDeptDto = PojoUtil.convert(ehmCompanyDeptVo1 , EhmCompanyDeptDto.class);
                ehmCompanyApi.update(ehmCompanyDto);
                ehmCompanyDeptApi.update(ehmCompanyDeptDto);
            }else{
                return RetMsg.failed("企业或者科室已删除");
            }
        }catch (ErrorCodeException e){
            e.printStackTrace();
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    /**
     * 根据身份证获取基本信息
     * @param card
     * @return
     */
    @RequestMapping(value = "/cardinfo", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg cardinfo(String card) {
        RetMsg msg = new RetMsg();
        try {
            if(!com.aijk.commons.lang.utils.IdcardUtil.validateCard(card)){
                msg.put("msg" , "错误身份证");
                msg.put("code" , -1);
                return msg;
            }

            BasUserQo qo = new BasUserQo();
            qo.setIdcard(card);
            List<BasUserVo> list = basUserApi.list(qo);
            if(list != null && list.size() > 0){
                Long uid = list.get(0).getId();
                EhmResidentQo ehmResidentQo = new EhmResidentQo();
                ehmResidentQo.setCompanyId(getCurrentUser().getCompanyId());
                ehmResidentQo.setUid(uid);
                List<EhmResidentVo> ehmResidentVoList = ehmResidentApi.list(ehmResidentQo);
                if(ehmResidentVoList != null && ehmResidentVoList.size() > 0){
                    msg.put("msg" , "该身份证已在企业注册");
                    msg.put("code" , -1);
                    return msg;
                }
                list.get(0).setAge(IdcardUtil.getAge(list.get(0).getIdcard()));
                msg.put("data" , list.get(0));
            }
            msg.put("code" , 0);
        }catch (ErrorCodeException e){
            e.printStackTrace();
            msg.put("msg" , "请求失败");
            msg.put("code" , -1);
        }
        return msg;
    }

    /**
     * 判断账号是否占用
     * @param validation
     * @return
     */
    @RequestMapping(value = "/validations", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg validation(String validation) {
        RetMsg msg = new RetMsg();
        try {
            EhmResidentQo qo  =new EhmResidentQo();
            qo.setCompanyId(getCurrentUser().getCompanyId());
            qo.setWorkno(validation);
            List<EhmResidentVo> list = ehmResidentApi.list(qo);
            if(list != null && list.size() > 0){
                msg.put("code" , -1);
            }else{
                msg.put("code" , 0);
            }
        }catch (ErrorCodeException e){
            e.printStackTrace();
            msg.put("code" , -1);
        }
        return msg;
    }

//    /**
//     * 逻辑删除
//     * @param id
//     * @return
//     */
//    @RequestMapping(value = "/open", method = RequestMethod.POST)
//    @ResponseBody
//    public RetMsg open(@RequestParam(value = "id") Long id) {
//        try {
//            EhmResidentVo entity = ehmResidentApi.findOne(id);
//            //判断部门是否删除
//
//            if(null != entity){
//                if(entity.getStatus() != null){
//                    int state = entity.getStatus() & 0xff;
//                    if(state == 10){
//                        entity.setStatus((byte)20);
//                    }else{
//                        entity.setStatus((byte)10);
//                    }
//                }else{
//                    entity.setStatus((byte)10);
//                }
//                EhmResidentDto dto = PojoUtil.convert(entity , EhmResidentDto.class );
//                ehmResidentApi.update(dto);
//                //企业修改人数
//                //部门修改人数
//            }
//        }catch (ErrorCodeException e){
//            e.printStackTrace();
//            return RetMsg.failed();
//        }
//        return RetMsg.success();
//    }

    @RequestMapping(value = "/excelcreate", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg excelCreate( HttpServletRequest request, HttpServletResponse response) {
        RetMsg retMsg = new RetMsg();
        try {
            String pathurl = request.getServletContext().getRealPath("") + "download/";
            String[] handers = {"姓名", "身份证", "手机号", "部门", "工号", "在职状态"}; //列标题

            //下拉框数据
            List<String[]> downData = new ArrayList();
            String[] str1 = null;
            String[] str2 = {"在职" , "退休" , "离职"};

            EhmCompanyVo ehmCompanyVo = ehmCompanyApi.findOne(getCurrentUser().getCompanyId());
            String fileName = "员工模板.xls"; //模板名称

            EhmCompanyDeptQo ehmCompanyDeptQo = new EhmCompanyDeptQo();
            ehmCompanyDeptQo.setCompanyId(getCurrentUser().getCompanyId());
            ehmCompanyDeptQo.setStatus((byte)10);
            List<EhmCompanyDeptVo> list = ehmCompanyDeptApi.list(ehmCompanyDeptQo) ;

            if (list != null && list.size() > 0) {
                str1 = new String[list.size()];
                for (int i = 0, len = list.size(); i < len; i++) {
                    str1[i] = list.get(i).getId() + "-" + list.get(i).getTitle();
                }
            } else {
                str1 = new String[]{};
                retMsg.put("msg", "该企业下无部门,请维护");
                retMsg.put("code", 1);
                return retMsg;
            }
            downData.add(str2);
            downData.add(str1);

            String[] downRows = {"5",  "3"}; //下拉的列序号数组(序号从0开始)
            File files = ExcelUtils.createExcelTemplate(pathurl + fileName, handers, downData, downRows);
            retMsg.put("path", request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort()
                    + "/download/"
                    + fileName);
            retMsg.put("code", 0);
        } catch (Exception e) {
            e.printStackTrace();
            retMsg.put("code", -1);
        }
        return retMsg;
    }

    @RequestMapping(value = "/edit/excel", method = RequestMethod.GET)
    public String edit_excel(Model model) {
        return "ehm/user/excel_edit";
    }

    @RequestMapping(value = "/excelread", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg excelRead2(@RequestParam(value = "file", required = true) MultipartFile file,  HttpServletRequest request) {
        try {
            if (file != null) {
                String path_date = DateUtil.dateFormate(new Date(), "yyyy-MM-dd");
                String path = "/upload/user/" + path_date;
                String fileName = file.getOriginalFilename();
                fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "-" + System.currentTimeMillis() + "." + fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    file.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                EhmCompanyDeptQo ehmCompanyDeptQo = new EhmCompanyDeptQo();
                ehmCompanyDeptQo.setCompanyId(getCurrentUser().getCompanyId());
                ehmCompanyDeptQo.setStatus((byte)10);
                List<EhmCompanyDeptVo> list = ehmCompanyDeptApi.list(ehmCompanyDeptQo);

                EhmResidentQo ehmResidentQo = new EhmResidentQo();
                ehmResidentQo.setCompanyId(getCurrentUser().getCompanyId());
                List<EhmResidentVo> ehmResidentVoList = ehmResidentApi.list(ehmResidentQo);
                String workNo = "";
                if(null!=ehmResidentVoList && ehmResidentVoList.size()>0){
                    for (EhmResidentVo vo : ehmResidentVoList){
                        workNo+=vo.getWorkno()+",";
                    }
                }

                EhmCompanyVo ehmCompanyVo = ehmCompanyApi.findOne(getCurrentUser().getCompanyId());

                //获取所有该企业下的身份证
                EhmResidentQo residentQoe = new EhmResidentQo();
                residentQoe.setCompanyId(getCurrentUser().getCompanyId());
                List<EhmResidentVo> residentVoList = ehmResidentApi.list(residentQoe);
                HashMap<String , EhmResidentVo> residentVoHashMap = new HashMap<>();
                HashMap<String , BasUserVo> basUserMap = new HashMap<>();
                if(null!=residentVoList&& residentVoList.size()>0){
                    List<Long> uidInList = new ArrayList<>();
                    for (EhmResidentVo vo : residentVoList){
                        uidInList.add(vo.getUid());
                    }

                    BasUserQo basUserQo = new BasUserQo();
                    basUserQo.setInIds(uidInList);
                    List<BasUserVo> basUserVos = basUserApi.list(basUserQo);
                    HashMap<Long , String> userHashMap = new HashMap<>();
                    if(basUserVos!=null&& basUserVos.size()>0){
                        for (BasUserVo basUserVo : basUserVos){
                            userHashMap.put(basUserVo.getId() , basUserVo.getIdcard());
                            basUserMap.put(basUserVo.getIdcard() , basUserVo);
                        }
                        for (EhmResidentVo vo : residentVoList){
                            if(userHashMap.containsKey(vo.getUid())){
                                vo.setIdCard(userHashMap.get(vo.getUid()));
                            }
                        }
                        for (EhmResidentVo vo : residentVoList){
                            if(vo.getIdCard()!=null){
                                residentVoHashMap.put(vo.getIdCard() , vo);
                            }
                        }
                    }
                }

                return excelRead(targetFile,ehmCompanyVo , list , workNo , residentVoHashMap , basUserMap);
            } else {
                return RetMsg.failed();
            }
        } catch (ErrorCodeException e) {
            e.printStackTrace();
            return RetMsg.failed();
        }
    }

    public RetMsg excelRead(File file, EhmCompanyVo ehmCompanyVo, List<EhmCompanyDeptVo>  ehmCompanyDeptVoList , String workNo , HashMap<String , EhmResidentVo> residentVoHashMap ,HashMap<String , BasUserVo> basUserMap) {
        RetMsg msg = new RetMsg();
        String codemsg = "";
        HashSet<String> map = new HashSet<>();
        boolean flag = false;
        String title = "";
        String No = "";
        HSSFWorkbook wb = null;
        List<EhmResidentDto> list = new ArrayList<>();
        try {
            FileInputStream si = new FileInputStream(file);
            //初始化一个工作簿
            wb = new HSSFWorkbook(si);
            //第一张表单
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum() + 1;  //row行初始行数位0;
            System.out.println("sheet表行数为：" + rowNum);   //打印总行数
            //上传的Excel表带有表头，所以从第二行开始，索引为1 ;
            for (int i = 1; i < rowNum; i++) {   //索引从0开始,即为表的第1行;
                EhmResidentDto ehmResident = new EhmResidentDto();
                ehmResident.setStatus((byte)10);
                ehmResident.setCreated(new Date());
                ehmResident.setCreater(Utils.toLong(getCurrentUser().getAdminId()));
                ehmResident.setCompanyId(ehmCompanyVo.getId());
                ehmResident.setCompany(ehmCompanyVo.getTitle());
                ehmResident.setCompanySn(ehmCompanyVo.getSn());

                ehmResident.setSalt(RandomString.generateRandomString(16));
                ehmResident.setPassword(PasswordHelper.encryptPassword("123456", ehmResident.getSalt()));

                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                flag = false;
                for (int j = 0; j < cellNum; j++) {
                    if (cellNum == 7) {
                        break;
                    }

                    Cell cell = row.getCell(j);
                    String cellValue = null;
                    if (cell != null) {
                        if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {// 对字符串的处理
                            cellValue = cell.getStringCellValue();
                        } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {// 对布尔值的处理
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                        } else if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {     //对数字的处理
                            cellValue = new BigDecimal(cell.getNumericCellValue()) + "";
                        }
                        // 下面按照数据出现位置封装到实体类中
                        switch (j) {
                            case 0:
                                if (!StringUtil.isEmpty(cellValue)) {
                                    ehmResident.setTitle(cellValue);
                                    title = cellValue+"  ";
                                } else {
                                    flag = true;
                                }
                                break;
                            case 1:
                                if(com.aijk.commons.lang.utils.IdcardUtil.validateCard(cellValue)){
                                    if(residentVoHashMap.containsKey(cellValue)){
                                        flag = true;
                                    }
                                    for (EhmResidentDto dto:list){
                                        if(dto.getIdCard().equals(cellValue)){
                                            flag = true;
                                        }
                                    }
                                    if(basUserMap.containsKey(cellValue)){
                                        ehmResident.setUid(basUserMap.get(cellValue).getId());
                                    }

                                    ehmResident.setSex(Utils.toShort(IdcardUtil.getSex(cellValue)));
                                    ehmResident.setIdCard(cellValue);
                                    ehmResident.setAge(IdcardUtil.getAge(cellValue));
                                }else{
                                    flag = true;
                                }
                                break;
                            case 2:
                                if (!StringUtil.isEmpty(cellValue)) {
                                    ehmResident.setCellphone(cellValue);
                                }
                                break;
                            case 3:
                                if (!StringUtil.isEmpty(cellValue)) {
                                    Long id = Utils.toLong(cellValue.split("-")[0]);
                                    boolean ischeck = false;
                                    for (EhmCompanyDeptVo vo : ehmCompanyDeptVoList) {
                                        if (id == vo.getId()) {
                                            ischeck = true;
                                        }
                                    }
                                    if (ischeck) {
                                        ehmResident.setDeptId(id);
                                        ehmResident.setDept(cellValue.split("-")[1]);
                                    } else {
                                        flag = true;
                                    }
                                } else {
                                    flag = true;
                                }
                                break;
                            case 4:
                                if (!StringUtil.isEmpty(cellValue)) {
                                    if(workNo.contains(cellValue)){
                                        flag = true;
                                    }else{
                                        if(No.contains(cellValue)){
                                            flag = true;
                                        }else{
                                            ehmResident.setWorkno(cellValue);
                                            No +=cellValue+",";
                                        }
                                    }
                                }
                                break;
                            case 5:
                                if (!StringUtil.isEmpty(cellValue)) {
                                    if(cellValue.equals("在职")){
                                        ehmResident.setJstatus(Utils.toShort(0));
                                    }else if(cellValue.equals("退休")){
                                        ehmResident.setJstatus(Utils.toShort(1));
                                    }else if(cellValue.equals("离职")){
                                        ehmResident.setJstatus(Utils.toShort(2));
                                    }
                                }
                                break;
                        }
                    }
                }
                if (flag) {
                    map.add(title);
                    continue;
                } else {
                    list.add(ehmResident);
                }
            }

            if (null != list && list.size() > 0) {
                saveUserList(list);
            }

            List<String> msgList = new ArrayList<>();
            msgList.addAll(map);

            if(msgList.size() > 0){
                for (String str : msgList)
                    codemsg+=str;

                msg.put("msg", codemsg+"等错误名单");
            }else{
                msg.put("msg", "0");
            }
            msg.put("code", 0);
        } catch (Exception e) {
            e.printStackTrace();
            msg.put("code", -1);
        }
        return msg;
    }


}
